import { Message } from 'element-ui'
const cache = {

}
function getId(){
    return 'default'
}
function downloadFile({href,fileName}){
    let aEle = document.createElement('a');
    aEle.href = href;
    aEle.download = fileName;
    document.querySelector('body').appendChild(aEle)
    aEle.click()
    aEle = null;
}
export default {
    install(Vue, options){
        Vue.prototype.getExcel = function({callback, params, id}){
            id = id || getId()
            if(cache[id]){
                Message({
                    message: '正在拼命加载中。。。',
                    type: 'warning',
                })
                return cache[id]
            }
            cache[id] = callback(params).then(res => {
                delete cache[id]
                if(res.code == '200'){
					let name = res?.data?.split?.('/').pop()
					if(!res.data){
						throw new Error('返回的下载地址为空')
					}
                    downloadFile({
                        href: res.data,
                        fileName: name
                    })
                    return Message({
                        message: '正在下载',
                        type: 'success',
                    })
                }else if(res.code === -1){
					Message({
						message: res.msg || '接口处理发生异常',
						type: 'info',
					})
				}else {
					throw new Error(res.msg)
				}
            }).catch(err => {
                // error
                Message({
                    message: err || 'Error',
                    type: 'error',
                })
            })
            return cache[id]
        }
    }
}
